from django_redis import get_redis_connection
from django.contrib.auth import authenticate, login, logout
from ihome.utils.mixins import LoginRequiredJSONMixin
import json, re
from django.conf import settings
from qiniu import Auth, put_data

from .models import User

from django import http
from django.http import JsonResponse
from django.views import View

from django_redis import get_redis_connection

from users.models import User

from logging import getLogger

logger = getLogger('ihome')

# 用户中心
class UserInfoView(View):
    """用户中心"""

    def get(self, request):
        info_data = {
            "avatar_url": settings.QINIU_URL + str(request.user.avatar),
            "create_time": request.user.date_joined,
            "name": request.user.username,
            "mobile": request.user.mobile,
            "user_id": request.user.id,
        }
        return JsonResponse({"data": info_data,
                             "errmsg": "OK",
                             "errno": "0"
                             })

# 用户头像上传
class UploadPhotoView(LoginRequiredJSONMixin, View):
    def post(self, request):
        # 1提取参数
        user = request.user
        avatar = request.FILES.get('avatar')
        # 2校验参数
        if not avatar:
            return JsonResponse({
                'code': 4002,
                'errmsg': '文件参数不存在'
            })
        else:
            access_key = settings.QINIU_ACCESS_KEY

            secret_key = settings.QINIU_SECRET_KEY
            # 构建鉴权对象
            q = Auth(access_key, secret_key)
            # 要上传的空间－七牛云的空间
            bucket_name = 'ihome-41'
            # 上传后保存的文件名
            key = None
            # 生成上传 Token，可以指定过期时间等
            token = q.upload_token(bucket_name, key, )
            # 要上传文件的本地路径
            ret, info = put_data(up_token=token, key=key, data=avatar.read())
            print(info)

            image_file = settings.QINIU_URL + ret['hash']
            print(image_file)

            print(ret['hash'])
            user = User.objects.get(pk=user.id)
            user.avatar = ret['hash']
            user.save()

            # 3业务数据处理

            # 4构建响应
            data = {"avatar_url": image_file}
        return JsonResponse({
            'errno': 0,
            'errmsg': '头像上传成功',
            'data': data
        })


#修改用户名
class ChangeUsernameView(View):
    """修改用户名"""
    def put(self, request):
        data = json.loads(request.body.decode())
        name = data.get('name')

        if not name:
            return JsonResponse({'errno': 4002, 'errmsg': '无用户名'})
        #name检验
        if not re.match(r'^[a-zA-Z0-9_\u4e00-\u9fa5]{3,20}$', name):
            return JsonResponse({'errno': 4004, 'errmsg': 'name格式有误！'})

        #修改用户名
        try:
            user = request.user
            user.username = name
            user.save()

        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4004, 'errmsg': '修改用户名失败'})

        response = JsonResponse({'errno': 0, 'errmsg': '修改成功'})
        return response

#用户名认证
class RealUsernameView(View):

    def post(self, request):
        '''接收参数'''
        json_bytes = request.body
        json_str = json_bytes.decode()
        json_dict = json.loads(json_str)

        real_name = json_dict.get('real_name')
        id_card = json_dict.get('id_card')

        if not all([real_name, id_card]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数！'})
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', real_name):
            return JsonResponse({'code': 400, 'errmsg': '姓名格式有误'})

        if not re.match(r'^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$',
                        id_card):
            return  JsonResponse({'code': 400, 'errmsg': '身份证号码格式有误！'})

            # 5.保存到数据库
        try:
            user = request.user
            user.real_name = real_name
            user.id_card = id_card
            user.save()
        except Exception as e:
            print(e)
            return http.JsonResponse({'code': 400, 'errmsg': '注册失败!'})

            # 6.拼接json返回
        return http.JsonResponse({'code': 0, 'errmsg': '认证信息保存成功!'})

    def get(self, request):
        user = request.user
        data = {'real_name': user.real_name,
                'id_card': user.id_card}
        return JsonResponse({
            'errno': '0',
            'errmsg': 'ok',
            'data': data
        })

# /api/v1.0/users注册
class RegisterView(View):
    def post(self, request):
        req_data = json.loads(request.body)
        mobile = req_data.get('mobile')
        phonecode = req_data.get('phonecode')
        password = req_data.get('password')
        if not all([password, mobile]):
            return JsonResponse({
                'errno': 400,
                'errmsg': '缺少必传参数'
            })

        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return JsonResponse({'errno': 400,
                                 'errmsg': 'password格式错误'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'errno': 400,
                                 'errmsg': '手机号格式错误'})

        # 短信验证码是否正确
        redis_conn=get_redis_connection('verify_code')
        sms_code_data=redis_conn.get('sms_%s' % mobile)

        if sms_code_data is None:
            return JsonResponse({
                'errno': 400,
                'errmsg': '短信验证码过期'
            })

        if sms_code_data.lower() != phonecode.lower():
            return JsonResponse({
                'errno': 400,
                'errmsg': '验证码有误'
            })

        # 2. 将用户数据保存到数据库
        try:
            user = User.objects.create_user(username=mobile, password=password, mobile=mobile)
        except Exception as e:
            return JsonResponse({
                'errno': 400,
                'errmsg': '操作数据库失败'
            })

        # 注册即登录功能：将用户的信息存入session，表示用户已经登录了
        from django.contrib.auth import login
        login(request, user)

        # 3.返回响应
        response = JsonResponse({

            "errno": "0",
            "errmsg": "注册成功"
        })
        # 设置 cookie 保存 username 用户名
        response.set_cookie('username',
                            user.username,
                            max_age=3600 * 24 * 14)
        return response


# /api/v1.0/session登录
class LoginView(View):
    def post(self, request):
        req_data = json.loads(request.body)
        username=req_data.get('mobile')
        password=req_data.get('password')
        if not all([username, password]):
            return JsonResponse({
                'errno': 400,
                'errmsg': '缺少必传参数'
            })

        user =authenticate(username=username, password=password)
        if user is None:
            return JsonResponse({
                'errno': 400,
                'errmsg': '用户名或密码错误'
            })
        login(request, user)
        response = JsonResponse({
            'errno': 0,
            'errmsg': '登录成功'
        })
        # 设置 cookie 保存 username 用户名
        response.set_cookie('username',
                            user.username,
                            max_age=3600 * 24 * 14)
        return response



    def get(self, request):
        #  从cookie获取
        cookie_data = request.COOKIES.get('username')

        if cookie_data:
            return JsonResponse({

                "errno": "0",
                "errmsg": "已登录",
                "data": {
                    "name": request.user.username
                }

            })
        else:
            return JsonResponse({

                "errno": "4101",
                "errmsg": "未登录"

            })


    def delete(self, request):
        logout(request)
        response = JsonResponse({

            "errno": "0",
            "errmsg": "已退出"

        })
        response.delete_cookie('username')

        return response

